﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco.cms.businesslogic.member;
using Vega.USiteBuilder;
using SPCFMedicineInformer.Members;
using SPCFMedicineInformer.Constants;
using System.Text;
using SPCFMedicineInformer.DocumentTypes;
using umbraco;
using umbraco.cms.businesslogic.web;
using System.Data;
using SPCFMedicineInformer.Helpers;
namespace SPCFMedicineInformer.Masterpages
{
    public partial class Admin_CustomerDetails : System.Web.UI.MasterPage
    {
        int id = 0;
        public static string user = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            int tempInt;
            id = Request.QueryString["id"] != null ? int.TryParse(Request.QueryString["id"].ToString(), out tempInt) ? tempInt : 1 : 0;
            btnDelete.Visible = id > 0 ? true : false;
            if (!IsPostBack)
            {
                LoadDates();
                if (id > 0)
                {
                    var m = MemberHelper.GetMemberById(id) as WebUser;
                    if (m != null)
                    {
                        txtEmail.Text = m.Email;
                        txtFirstname.Text = m.Fistname;
                        txtLastname.Text = m.Lastname;
                        user = m.Email.ToLower();
                        rdoGender.Text = m.Gender;
                        btnActivate.Text = m.IsInactive ? "Activate" : "Deactivate";

                        txtAddress.Text = m.Address;


                        DateTime bDate;
                        if (DateTime.TryParse(m.Birthdate, out bDate))
                        {
                            ddlMonth.SelectedValue = bDate.Month.ToString();
                            ddlDay.SelectedValue = bDate.Day.ToString();
                            ddlYear.SelectedValue = bDate.Year.ToString();
                        }
                        BindGrid();
                        ShowContent(true);
                    }
                    else
                    {
                        ShowContent(false);
                    }
                    
                }
                else
                {
                    ShowContent(true);
                }
            }
        }
        void ShowContent(bool b)
        {
            plcContent.Visible = b;
            plcError.Visible = !b;
        }
        void BindGrid()
        {
            var consultations = NodeLocator.GetNodesOfExactType<DocumentTypes.Consultation>().Where(a => a.User.ToLower() == user).ToList().OrderByDescending(node => node.CreateDate);
            rptConsultations.DataSource = consultations;
            rptConsultations.DataBind();
        }
        void Update()
        {
            if (id > 0)
            {
                var m = new Member(id);
                if (m != null)
                {
                    TransferDetailsToUmbraco(m);
                }
                
            }
        }
        void TransferDetailsToUmbraco(Member m)
        {
            string birthdate = string.Concat(ddlMonth.Items[ddlMonth.SelectedIndex].Text, " ", ddlDay.Items[ddlDay.SelectedIndex].Text, " ,", ddlYear.Items[ddlYear.SelectedIndex].Text);
            m.Email = txtEmail.Text;
            m.LoginName = txtEmail.Text;
            if (plcChangePassword.Visible)
                m.Password = txtNewPassword.Text;
            m.getProperty(UmbracoPropertyName.MEMBER_FIRSTNAME).Value = txtFirstname.Text;
            m.getProperty(UmbracoPropertyName.MEMBER_LASTNAME).Value = txtLastname.Text;
            m.getProperty(UmbracoPropertyName.MEMBER_GENDER).Value = rdoGender.Text;
            m.getProperty(UmbracoPropertyName.MEMBER_ADDRESS).Value = txtAddress.Text;
            m.getProperty(UmbracoPropertyName.MEMBER_BIRTHDATE).Value = birthdate;
            m.Save();
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Helpers.FormValidation.ValidateRegistration(MsgLiteral,txtFirstname.Text,
                txtLastname.Text,txtNewPassword.Text,txtConfirmPassword.Text,txtEmail.Text,id,plcChangePassword.Visible,rdoGender.Text,ddlMonth,ddlDay,ddlYear))
            {
                Update();
                var sb = new StringBuilder();
                var msgFormat = "<p class=\"{0}\">{1}</p>";
                sb.AppendLine(string.Format(msgFormat, "msg done", "Member Successfully Saved!"));
                MsgLiteral.Visible = true;
                MsgLiteral.Text = sb.ToString();
                ShowNewPassword(false);
            }
            
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/members/active-members");
        }
        protected void lbChangePassword_Click(object sender, EventArgs e)
        {
            ShowNewPassword(true);
        }
        void ShowNewPassword(bool b)
        {
            plcChangePassword.Visible = b;
            lbChangePassword.Visible = !b;
        }
        void Delete(int idToDelete)
        {
            if (idToDelete > 0)
            {
                Document doc = new Document(idToDelete);
                if (doc.Published)
                {
                    doc.UnPublish();
                    library.UnPublishSingleNode(doc.Id);
                }
                doc.delete();
                BindGrid();
            }
        }
        protected void repeater_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int intTemp = 0;
            if (int.TryParse((string)e.CommandArgument, out intTemp))
            {
                switch (e.CommandName.ToLower())
                {
                    case "delete":
                        Delete(intTemp);
                        break;
                }
            }
        }
        void DeleteCustomer(int id)
        {

            if (id > 0)
            {
                Member m = new Member(id);
                if (m != null)
                {
                    m.delete();
                }
                Response.Redirect("/admin/members/active-members");
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            DeleteCustomer(id);
        }
        protected void btnActivate_Click(object sender, EventArgs e)
        {
            bool result = true;
            if (btnActivate.Text == "Activate")
                result = false;

            if (id > 0)
            {
                var m = new Member(id);
                if (m != null)
                {
                    m.getProperty(UmbracoPropertyName.MEMBER_IS_INACTIVE).Value = result;
                    m.Save();
                    btnActivate.Text = m.getProperty(UmbracoPropertyName.MEMBER_IS_INACTIVE).Value.ToString() == "1" ? "Activate" : "Deactivate";
                }
                
            }
        }
        void LoadDates()
        {
            DateTime dteDefault = DateTime.Parse("1/1/2012");
            DataTable dtMonth = new DataTable();
            DataTable dtDay = new DataTable();
            DataTable dtYear = new DataTable();
            DataRow dr = null;

            dtMonth.Columns.Add(new DataColumn("TextField"));
            dtMonth.Columns.Add(new DataColumn("ValueField"));
            dtDay = dtMonth.Copy();
            dtYear = dtMonth.Copy();

            string textField = "TextField";
            string valueField = "ValueField";

            dr = dtMonth.NewRow();
            dr[textField] = "Month";
            dr[valueField] = "0";
            dtMonth.Rows.Add(dr);
            for (int mon = 1; mon <= 12; mon++)
            {
                dr = dtMonth.NewRow();
                dr[textField] = dteDefault.ToString("MMMM");
                dr[valueField] = mon;
                dtMonth.Rows.Add(dr);
                dteDefault = dteDefault.AddMonths(1);
            }


            dr = dtDay.NewRow();
            dr[textField] = "Day";
            dr[valueField] = "0";
            dtDay.Rows.Add(dr);
            for (int day = 1; day <= 31; day++)
            {
                dr = dtDay.NewRow();
                dr[textField] = day;
                dr[valueField] = day;
                dtDay.Rows.Add(dr);
            }

            dr = dtYear.NewRow();
            dr[textField] = "Year";
            dr[valueField] = "0";
            dtYear.Rows.Add(dr);
            for (int year = DateTime.Now.Year; year >= DateTime.Now.AddYears(-85).Year; year--)
            {
                dr = dtYear.NewRow();
                dr[textField] = year;
                dr[valueField] = year;
                dtYear.Rows.Add(dr);
            }

            FormHelper.BindDropDown(ddlDay, dtDay, textField, valueField);
            FormHelper.BindDropDown(ddlMonth, dtMonth, textField, valueField);
            FormHelper.BindDropDown(ddlYear, dtYear, textField, valueField);
        }
    }
}